var app = getApp(), fetchApi = require("../../../../utils/httpPost.js"),
formatTime = require("../../../../component/common.js")
import Toast from '../../../../component/vant/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    
    date: {
      maxRange: [],
      selectSingle: null,
      selectRange: [],
      selectMultiple: [],
      quickSelect1: null,
      quickSelect2: [],
      customColor: [],
      customConfirm: [],
      customRange: null,
      customDayText: [],
      customPosition: null,
    },
    type:'',
    round: true,
    color: '',
    minDate: new Date(2022, 3, 1).getTime(),
    maxDate: new Date(2027, 12, 31).getTime(),
    maxRange: null,
    position: 'bottom',
    formatter: null,
    showConfirm: true,
    confirmText: '确定',
    confirmDisabledText: '确定',

    showPopProductType:false,
    productTypes:[],
    typeNames:[],
    type_name:'',
    activeTime:'',
    isLoading:false,
    currentTab:0,
    submitState:false,
    fileList0:[],
    fileList1: [],
    deleteImgIds:'',
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    mer_id:0,
    rules:[],//规格列表
    rule_names:[],
    rule_name:'',
    rule_values:[],
    manyFormValidate: [],
    isShowPopup:false,
    showCalendar:false,//活动期限
    isReset:0,
    product:{
      id: 0,
      image: '',//商品缩略图
      sliderImage: '',//轮播图
      storeName: '',//商品名称
      storeInfo: '',//简介
      keyword: '',//关键字
      ruleId:0,//规格id
      sort: '',//索引
      isSale:1,
      isLimit: 0,
      limitCount:100,
      cateId:2,
      cateChildId:0,
      ruleId:0,
      isShow: 0,
      isBest: 1,
      isNew: 1,
      isCoupon:0,
      description: '',//商品描述
      isSub: 1,
      isActive:0,
      subType: 1,
      specType: '0',
      isAppointment:1,
      isVisit:1,
      voucherId:0,//消费券
      productAttr:[],
      productValue:[],
      sliderImageArray:[],
      //商品属性
      attrs:[
        {
          name:'默认',
          id:0,
          price:0,
          otPrice:0,
          stock:0, 
        }
      ],
      items:[],
      header:[],
      activeDateRange:[],//活动时间区间
      productImgs:[],
      sliderImgs:[],
    },
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options', options)
    var that = this
    var isLogin = app.getStorageSync("isLogin");
    console.log('isLogin',isLogin)

    if(options.mer_id){
      this.data.mer_id = parseInt(options.mer_id)
    }

    if(options.product_id){
      this.data.product.id = parseInt(options.product_id);
    }
    // if(this.data.product_id > 0){
    // }
    this.onHttpInit();
  },
  handleChange({ detail }) {
    console.log('handleChange',detail)
    var that = this;
    that.setData({
      currentTab: detail.index,
    });
    if(detail.index == 3){
      // this.selectComponent('#hf_editor').setHtml('<p>把小蛋糕敲晕了再吃，</p><p>安抚可乐等气消了再喝，</p><p>夹心饼干劝分了再喝牛奶，</p><p>讲个笑话把冰块气哭了再咬。</p>');
      this.selectComponent('#hf_editor_1').setHtml(this.data.product.buyingTips);
    } else if(detail.index == 4){
      // this.selectComponent('#hf_editor').setHtml('<p>把小蛋糕敲晕了再吃，</p><p>安抚可乐等气消了再喝，</p><p>夹心饼干劝分了再喝牛奶，</p><p>讲个笑话把冰块气哭了再咬。</p>');
      this.selectComponent('#hf_editor').setHtml(this.data.product.description);
    }
  },
  onChangeRule(){
    this.setData({
      isShowPopup: !this.data.isShowPopup
    })
  },
  onChangeProductType(){
    this.setData({
      showPopProductType: !this.data.showPopProductType
    })
  },
  onConfirmRule(e){
    console.log('onConfirmRule',e)
    var index = e.detail.index;
    var name = this.data.rule_names[index];
    var rule_id = this.data.rules[index].id;
    
    this.data.product.ruleId = rule_id;
    var ruleValue = this.data.rules[index].ruleValue;
    var valueArray = JSON.parse(ruleValue);
    console.log('valueArray',valueArray)
    var ruleValueArray = this.data.rules[index].ruleValueArray;
    this.data.product.items = ruleValueArray
    this.setData({
      rule_values:valueArray[0].detail,
      rule_name:name,
      isShowPopup:false
    })
    this.resetAttr(this.data.product.specType,valueArray);
    
    this.onHttpIsFormatAttr(ruleValueArray);
  },
  onConfirmProductType(e){
    console.log('onConfirmProductType',e);
    var index = e.detail.index;
    var name = this.data.typeNames[index];
    var childTypeId = this.data.productTypes[index].id;
    this.data.product.cateChildId = childTypeId;
    
    this.setData({
      type_name: name,
      showPopProductType:false
    })

  },
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/product/detail', {
      product_id: that.data.product.id,
      mer_id: that.data.mer_id,
      is_mer_edit:1,
    }, function (res) {
      console.log("获取商品信息数据", res)
      if (res.data.code == 0) {

        var activeTime = res.data.data.product!=undefined && res.data.data.product.activeTime!=undefined ? 
                          res.data.data.product.activeTime : "";

        var fileList0 = res.data.data.product!=undefined && res.data.data.product.productImgs!=undefined ? 
                          res.data.data.product.productImgs : [];
        
        var fileList1 = res.data.data.product!=undefined && res.data.data.product.sliderImgs!=undefined ? 
                          res.data.data.product.sliderImgs : [];

        that.setData({
          product: res.data.data.product!=undefined? res.data.data.product : that.data.product,
          activeTime: activeTime,
          rules: res.data.data.rules,
          rule_names: res.data.data.rule_names,
          rule_name:res.data.data.rule_name,
          productTypes:res.data.data.types,
          typeNames:res.data.data.type_names,
          fileList0: fileList0,
          fileList1: fileList1,
        })
        // that.onHttpIsFormatAttr(res.data.data.product.rule.ruleValueArray)
      }
      // else{
      //   Toast.fail(res.data.msg)
      // }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  onHttpIsFormatAttr: function (ruleValueArray) {
    var that = this;
    fetchApi.httpPost('/product/isFormatAttr', {
      product_id: that.data.product.id,
      is_reset: that.data.isReset,
      jsonStr: ruleValueArray,
    }, function (res) {
      console.log("获取商品信息数据", res)
      if (res.data.code == 0) {
        that.data.product.attrs = res.data.data.value;
        that.data.product.header = res.data.data.header;
        that.setData({
          product: that.data.product,
          value: res.data.data.value,
          header: res.data.data.header,
        })
      }else{
        Toast.fail(res.data.msg)
      }
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false, })
    })
  },
  productInput: function (e) {
    console.log('productInput',e)
    var key = e.currentTarget.dataset.key;
    if(key == 'storeName'){
      this.data.product.storeName = e.detail;
    } else if(key == 'storeInfo'){
      this.data.product.storeInfo = e.detail;
    } else if(key == 'keyword'){
      this.data.product.keyword = e.detail;
    } else if(key == 'sort'){
      this.data.product.sort = e.detail;
    }else if(key == 'limitCount'){
      this.data.product.limitCount = e.detail;
    }
  },
  attrInput(e){
    console.log('')
    var key = e.currentTarget.dataset.key;
    console.log("key" ,key)
    console.log("value" ,e.detail)
    console.log("this.data.product.attrs",this.data.product.attrs)
    if(key == 'name'){
      if(e.detail.value !=''){
        this.data.product.attrs[0].name = e.detail;
      }
      
    } else if(key == 'price'){
      if(e.detail.value !=''){
        this.data.product.attrs[0].price = parseFloat(e.detail);
      }
      
    } else if(key == 'otPrice'){
      if(e.detail.value !=''){
        this.data.product.attrs[0].otPrice = parseFloat(e.detail);
      }
      
    } else if(key == 'stock'){
      if(e.detail.value !=''){
        this.data.product.attrs[0].stock =parseInt(e.detail);
      }
    }
  },
  onChangeRadio(e){
    console.log('onChangeRadio',e)
    var key = e.currentTarget.dataset.key;
    if(key == 'isAppointment'){
      this.data.product.isAppointment = parseInt(e.detail);
    } else if(key == 'isVisit'){
      this.data.product.isVisit = parseInt(e.detail);
    } else if(key == 'isCoupon'){
      this.data.product.isCoupon = parseInt(e.detail);
    } else if(key == 'isShow'){
      this.data.product.isShow = parseInt(e.detail);
    } else if(key == 'isLimit'){
      this.data.product.isLimit = parseInt(e.detail);
    } else if(key == 'specType'){
      this.data.product.specType = e.detail;//parseInt();
      // this.data.product.attrs = [];
      this.data.product.items = [];
      // this.resetAttr(this.data.product.specType)
    } else if(key == 'isActive'){
      this.data.product.isActive = parseInt(e.detail);
      // if(this.data.product.isActive == 1){
      //   this.setData({
      //     showCalendar : true,
      //   })
      // }
    }


    this.setData({
      product: this.data.product
    })
  },
  /**
   * 重新生成 规格json数组
   * @param {*} specType 
   */
  resetAttr(specType,valueArray){
    if(specType == 0){//单规格
      this.data.product.attrs = [{
          name:'默认',
          id:0,
          price:0,
          otPrice:0,
          stock:0, 
        }]
      this.setData({
        product: this.data.product
      })
    } else {//多规格
      var valueArrayNames = [];
      if(valueArray.length > 0){
        valueArrayNames = valueArray[0].detail;
      }
      console.log('resetAttr valueArray',valueArray)
      console.log('resetAttr rules',this.data.rules)
      console.log('attrs',this.data.product.attrs)
      if(this.data.product.attrs !=undefined){
        if(this.data.product.attrs.length == 0){
          for(var index in valueArrayNames){
            var attrNode = {
              name:valueArrayNames[index],
              id:0,
              price:0,
              otPrice:0,
              stock:0, 
            };
            // attrNode.name = valueArrayNames[index];
            this.data.product.attrs.push(attrNode)
          }
        }
      }else{
        this.data.product.attrs = [];
        for(var index in valueArrayNames){
          var attrNode = {
            name:valueArrayNames[index],
            id:0,
            price:0,
            otPrice:0,
            stock:0, 
          };
          // attrNode.name = valueArrayNames[index];
          this.data.product.attrs.push(attrNode)
        }
      }

      this.setData({
        product: this.data.product
      })
    }
  },
  submitOp:function(e){
    var that = this;
    console.log('product',this.data.product)
    if(this.data.currentTab == 0){
      if(that.data.product.storeName==''){
        Toast.fail("请输入商品名称");
        return ;
      }
      if(that.data.storeInfo == ''){
        Toast.fail("请选择商品简介");
        return ;
      }
    }
    if(this.data.currentTab > 0){
      if(that.data.product.id == 0){
        Toast.fail("请先保存商品基础参数");
        return ;
      }
    }
    if(this.data.currentTab == 2){
      if(that.data.fileList0.length  == 0){
        Toast.fail("请上传商品缩略图");
        return ;
      }
      if(that.data.fileList1.length  == 0){
        Toast.fail("请上传商品轮播图");
        return ;
      }
    }
    
    if(that.data.deleteImgIds!=undefined && that.data.deleteImgIds!=''){
      that.data.deleteImgIds = that.data.deleteImgIds.substring(0,that.data.deleteImgIds.length - 1);
    }
  

    that.setData({ submitting : true})
    fetchApi.httpPost('/product/add', {
      product:that.data.product,
      save_index:that.data.currentTab,
      product_id:that.data.product.id,
      mer_id:that.data.mer_id,
      deleteImgIds:that.data.deleteImgIds,
    }, function (res) {
      console.log('res', res)
      if (res.data.code == 0) {
        var product_id = res.data.data;
        console.log('product_id',product_id)
        that.data.product.id = product_id;
        if (product_id > 0 && that.data.currentTab == 2) {
          if(that.data.fileList0.length > 0){
            for (var index in that.data.fileList0) {
              if(that.data.fileList0[index].id == undefined){
                wx.uploadFile({
                  url: fetchApi.getPlatformUrl() + '/product/uploadImg',
                  filePath: that.data.fileList0[index].url,
                  name: 'file',
                  formData: { product_id: product_id, img_type : 0 },
                  success: function (res) {
                    console.log('uploadFile success res', res)
                  }, fail: function (res) {
                    console.log('uploadFile fail res', res)
                  }
                })
              }
            }
          }
          if (that.data.fileList1.length > 0) {
            for (var index in that.data.fileList1) {
              if(that.data.fileList1[index].id == undefined){
                wx.uploadFile({
                  url: fetchApi.getPlatformUrl() + '/product/uploadImg',
                  filePath: that.data.fileList1[index].url,
                  name: 'file',
                  formData: { product_id: product_id , img_type : 1},
                  success: function (res) {
                    console.log('uploadFile success res', res)
                  }, fail: function (res) {
                    console.log('uploadFile fail res', res)
                  }
                })
              }
            }
          }
        }
        

        Toast.success(res.data.msg);
        // setTimeout(function(){
        //   wx.switchTab({
        //     url: '/pages/home/home',
        //   })
        // },1000)

      } else {
        Toast.fail(res.data.msg);
      }
    },function(){})
  },
  getBuyingTipsHtml(e) {//从组件获取值
    this.data.product.buyingTips = e.detail.content.html
    console.log('getHtml',e.detail.content.html)
  },
  getHtml(e) {//从组件获取值
    this.data.product.description = e.detail.content.html
    console.log('getHtml',e.detail.content.html)
  },
  insertImage(){ //图片上传插入示例
    wx.chooseImage({
      count: 9,
      success: res => {
        console.log('insertImage',res);
        // 本地测试图片插入
        this.selectComponent('#hf_editor').insertSrc(res.tempFilePaths[0]);
        // wx.uploadFile({ //调用图片上传接口
        //   url: 'http://192.168.1.61:3000/upload', 
        //   filePath: res.tempFilePaths[0],
        //   name: 'imgFile',
        //   success: res => {
        //     let imgUrl = JSON.parse(res.data).url
        //     this.selectComponent('#hf_editor').insertSrc('http://192.168.1.61:3000' + imgUrl);//调用组件insertSrc方法
        //   }
        // })
      }
    })
  },
  insertImageTips(){ //图片上传插入示例
    wx.chooseImage({
      count: 9,
      success: res => {
        console.log('insertImage',res);
        // 本地测试图片插入
        this.selectComponent('#hf_editor_1').insertSrc(res.tempFilePaths[0]);
        // wx.uploadFile({ //调用图片上传接口
        //   url: 'http://192.168.1.61:3000/upload', 
        //   filePath: res.tempFilePaths[0],
        //   name: 'imgFile',
        //   success: res => {
        //     let imgUrl = JSON.parse(res.data).url
        //     this.selectComponent('#hf_editor').insertSrc('http://192.168.1.61:3000' + imgUrl);//调用组件insertSrc方法
        //   }
        // })
      }
    })
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  trim: function (t) {
    return t.replace(/(^\s*)|(\s*$)/g, "");
  },
  deleteImg0:function(res){
      console.log('删除图片',res)
      this.data.fileList0 = []
      this.setData({
        fileList0:this.data.fileList0
      })
  },
  deleteImg1:function(res){
      
      console.log('删除图片',res)
      var index = res.detail.index;
      console.log('删除图片 index',index)

      var file = this.data.fileList1[index];
      if(file.id!=undefined){
        this.data.deleteImgIds += file.id+",";
      }
      console.log('this.data.deleteImgIds',this.data.deleteImgIds);

      this.data.fileList1.splice(index,1);
      console.log('this.data.fileList1',this.data.fileList1)
      this.setData({
        fileList1:this.data.fileList1
      })

  },
  afterRead(event) {
    console.log('afterRead',event)
    const { file, name } = event.detail;
    console.log('afterRead name',name)
    console.log('afterRead file',file)
    const fileList = this.data[`fileList${name}`];
    console.log('fileList',fileList)
    this.setData({ [`fileList${name}`]: fileList.concat(file) });
    console.log('afterRead fileList',fileList)
    if(name == 0){
      this.data.fileList0.concat(file)
      console.log('fileList0',this.data.fileList0)
    } else if(name == 1){
      this.data.fileList1.concat(file)
      console.log('fileList1',this.data.fileList1)
    }
  },
  oversize() {
    wx.showToast({ title: '文件超出大小限制', icon: 'none' });
  },
  
  onConfirm(event) {
    console.log('onConfirm',event);
    this.setData({ showCalendar: false });
    // event.detail
    if(this.data.product.activeDateRange == undefined){
      this.data.product.activeDateRange = [];
    }
    
    var begin_date = formatTime.formatTimeTwo(event.detail[0],'Y-M-D')
    console.log('begin_date',begin_date)
    this.data.begin_date = begin_date;
    this.data.product.activeDateRange.push(this.data.begin_date);

    
    var begin_date_simgple = formatTime.formatTimeTwo(event.detail[0],'M-D')
    var end_date_simgple = formatTime.formatTimeTwo(event.detail[1],'M-D')

    var end_date = formatTime.formatTimeTwo(event.detail[1],'Y-M-D')
    console.log('end_date',end_date)
    this.data.end_date = end_date;
    this.data.product.activeDateRange.push(this.data.end_date);

    this.setData({
      activeTime: begin_date_simgple + ' ~ ' + end_date_simgple
    })

    console.log(' this.data.product.activeDateRange', this.data.product.activeDateRange)
  },
  onSelect(event) {
    console.log(event);
  },
  onClose() {
    console.log('onClose');
    this.setData({
      showCalendar: false,
    })
  },
  resetSettings() {
    this.setData({
      round: true,
      color: '',
      minDate: new Date(2021, 0, 10).getTime(),
      maxDate: new Date(
        new Date().getFullYear(),
        new Date().getMonth() + 6,
        new Date().getDate()
      ).getTime(),
      maxRange: null,
      position: 'bottom',
      formatter: null,
      showConfirm: true,
      confirmText: '确定',
      confirmDisabledText: '确定',
    });
  },
  showCalendar(event) {
    // this.resetSettings();
    const { type, id } = event.currentTarget.dataset;
    console.log('type',type)
    console.log('id',id)
    var data = {
      id,
      type,
      showCalendar: true,
    };

    switch (id) {
      case 'quickSelect1':
      case 'quickSelect2':
        data.showConfirm = false;
        break;
      case 'customColor':
        data.color = '#07c160';
        break;
      case 'customConfirm':
        data.confirmText = '完成';
        data.confirmDisabledText = '请选择结束时间';
        break;
      case 'customRange':
        data.minDate = new Date(2010, 0, 1).getTime();
        data.maxDate = new Date(2010, 0, 31).getTime();
        break;
      case 'customDayText':
        data.minDate = new Date(2010, 4, 1).getTime();
        data.maxDate = new Date(2010, 4, 31).getTime();
        data.formatter = this.dayFormatter;
        break;
      case 'customPosition':
        data.round = false;
        data.position = 'right';
        break;
      case 'maxRange':
        data.maxRange = 3;
        break;
    }
    this.setData(data);
  },
  dayFormatter(day) {
    const month = day.date.getMonth() + 1;
    const date = day.date.getDate();

    if (month === 5) {
      if (date === 1) {
        day.topInfo = '劳动节';
      } else if (date === 4) {
        day.topInfo = '五四青年节';
      } else if (date === 11) {
        day.text = '今天';
      }
    }

    if (day.type === 'start') {
      day.bottomInfo = '入店';
    } else if (day.type === 'end') {
      day.bottomInfo = '离店';
    }
    return day;
  },


})